package cn.chanel.mall.controller;

import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@Slf4j
@Controller
@RequestMapping("/file")
public class FileController {

    @RequestMapping("/{filename}")
    public void getImage(@PathVariable String filename, HttpServletResponse response) {
        if(StringUtils.hasText(filename)){
            var directory = FileUtils.getTempDirectory();
            var objImageFile = new File(directory, filename);
            if(objImageFile.exists()){
                try (var outputStream = response.getOutputStream()){
                    response.setContentType("image/png");
                    ImageIO.write(ImageIO.read(objImageFile), "png", outputStream);
                } catch (IOException e) {
                    System.out.println(e.toString());
                }
            }else {
                String retLog = "can't find image, descFile -> " + objImageFile.getAbsolutePath();
                log.error(retLog);
                response.setContentType("text/plain");
                response.setCharacterEncoding("UTF-8");
                try (val writer = response.getWriter()){
                    writer.write(retLog + "\n\n");
                    writer.write("硬盘上找不到此图片文件, 路径是 -> " + objImageFile.getAbsolutePath() + "\n\n");
                    writer.flush();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }

        }
    }
}
